const items = document.querySelector('.items')
const btn = document.querySelector('.btn')
class LotteryBox {
	items = []
	addItem(name, probability) {
		this.items.push({
			name,
			probability,
		})
	}
	generateArray(length) {
		const arr = []
		this.items.forEach(({ name, probability }) => {
			for (let i = Math.floor(probability * length); i > 0; i--) {
				arr.push(name)
			}
			arr.forEach(() => this.randomSwitch(arr))
		})
		return arr
	}
	randomSwitch(arr) {
		const idx1 = Math.floor(Math.random() * arr.length)
		const idx2 = Math.floor(Math.random() * arr.length)
		let tmp = arr[idx1]
		arr[idx1] = arr[idx2]
		arr[idx2] = tmp
	}
}

const lb = new LotteryBox()
lb.addItem('拍立得', 0.05)
lb.addItem('斑马', 0.15)
lb.addItem('彩虹糖', 0.25)
lb.addItem('小裙子', 0.35)
lb.addItem('五条悟', 0.1)
lb.addItem('手账', 0.1)
items.innerHTML = lb
	.generateArray(100)
	.map((name) => `<div class="item">${name}</div>`)
	.join('')

let i = 0,
	topMax = items.children.length * 40,
	started = false,
	timer
function roll() {
	timer = setInterval(() => {
		items.style.top = `-${i}vh`
		i += 4
		i %= topMax
	}, 5)
	started = true
}

btn.addEventListener('click', () => {
	if (started) {
		clearInterval(timer)
		i = Math.round(i / 40) * 40
		items.style.top = `-${i}vh`
		btn.style.transform = null
		setTimeout(() => {
			alert('截图发给你的男朋友吧！😁')
		}, 500)
		return
	}
	if (!verify()) return
	items.style.display = 'block'
	btn.style.transform = 'scaleY(-1)'
	roll()
})

function verify() {
	const date = new Date()
	if (localStorage.getItem('lottery')) {
		alert('你不是抽过了吗！😒😒😒')
		return false
	}
	if ((date.getMonth() === 1, date.getDate() === 12)) {
		if (prompt('你的生日是：（格式为：2019/4/5）') === '2004/10/17') {
			alert('欢迎！欢迎！请开始抽奖吧！🎉🎉🎉🎉🎉🎉')
			window.localStorage.setItem('lottery', true)
			return true
		}
		alert('你不是我的xlp喔，请离开吧！😜')
	} else {
		alert('还没到春节喔！😎')
	}
	return false
}
